package com.hua.yuan.common.https;
import android.annotation.SuppressLint;
import android.support.annotation.NonNull;
import com.zhy.http.okhttp.OkHttpUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;


/**
 * Created by hy on 2017/2/6.
 * OKHttp的管理类
 */

public class OkHttpModule {

    private  Retrofit retrofit;

    private  OkHttpClient mOkHttpClient;

    public static class Buidler{

        public static OkHttpModule INSTANCE=new OkHttpModule();
    }

    public static OkHttpModule getInstance(){
        return Buidler.INSTANCE;
    }

    /**
     * 初始化okHttpClient,这里面没有设置缓存
     *
     * @return OkHttpClient
     */
    public  void init(@NonNull String pBaseUrl) {
        SSLContext sslContext = HttpsUtil.cancleAllCard();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        if (sslContext != null) {
            builder.sslSocketFactory(sslContext.getSocketFactory())
                    .hostnameVerifier(new HostnameVerifier() {
                        @SuppressLint("BadHostnameVerifier")
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
        }
        mOkHttpClient=builder.connectTimeout(20000L, TimeUnit.MILLISECONDS)
                .readTimeout(20000L, TimeUnit.MILLISECONDS)
                .addNetworkInterceptor(netInterceptor)
                //其他配置
                .build();
        OkHttpUtils.initClient(mOkHttpClient);

        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(pBaseUrl).
                    client(mOkHttpClient).
                    addConverterFactory(ScalarsConverterFactory.create()).build();
        }
    }


    /**
     * 一、无论有无网路都添加缓存。
     * 目前的情况是我们这个要addNetworkInterceptor
     * 这样才有效。经过本人测试（chan）测试有效.
     * 60S后如果没有网络将获取不到数据，显示连接失败
     */
    private Interceptor netInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            int maxAge = 60;
            // 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        }
    };

    public  Retrofit getRetrofit() {
        return retrofit;
    }

}
